package com.ruoyi.luban.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.MD5Utils;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.luban.domain.*;
import com.ruoyi.luban.domain.dto.LoginDto;
import com.ruoyi.luban.domain.vo.LoginUserAndTokenVo;
import com.ruoyi.luban.domain.vo.WxLoginUserVo;
import com.ruoyi.luban.mapper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.luban.service.IPWxLoginUserService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 微信登录用户Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-01-28
 */
@Service
public class PWxLoginUserServiceImpl implements IPWxLoginUserService 
{
    @Autowired
    private PWxLoginUserMapper pWxLoginUserMapper;
    @Autowired
    private PDealerLoginMapper pDealerLoginMapper;
    @Autowired
    private PDealerMapper pDealerMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PSchoolMapper pSchoolMapper;
    @Autowired
    private PUserAddressMapper pUserAddressMapper;
    @Autowired
    private PFileInfoMapper fileInfoMapper;
    @Autowired
    private PWxUserMapper pWxUserMapper;
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 查询微信登录用户
     * 
     * @param id 微信登录用户主键
     * @return 微信登录用户
     */
    @Override
    public PWxLoginUser selectPWxLoginUserById(Long id)
    {
        return pWxLoginUserMapper.selectPWxLoginUserById(id);
    }

    /**
     * 查询微信登录用户列表
     * 
     * @param pWxLoginUser 微信登录用户
     * @return 微信登录用户
     */
    @Override
    public List<PWxLoginUser> selectPWxLoginUserList(PWxLoginUser pWxLoginUser)
    {
        return pWxLoginUserMapper.selectPWxLoginUserList(pWxLoginUser);
    }

    /**
     * 新增微信登录用户
     * 
     * @param pWxLoginUser 微信登录用户
     * @return 结果
     */
    @Override
    public int insertPWxLoginUser(PWxLoginUser pWxLoginUser)
    {
        pWxLoginUser.setCreateTime(DateUtils.getNowDate());
        return pWxLoginUserMapper.insertPWxLoginUser(pWxLoginUser);
    }

    /**
     * 修改微信登录用户
     * 
     * @param pWxLoginUser 微信登录用户
     * @return 结果
     */
    @Override
    public int updatePWxLoginUser(PWxLoginUser pWxLoginUser)
    {
        pWxLoginUser.setUpdateTime(DateUtils.getNowDate());
        return pWxLoginUserMapper.updatePWxLoginUser(pWxLoginUser);
    }

    /**
     * 批量删除微信登录用户
     * 
     * @param ids 需要删除的微信登录用户主键
     * @return 结果
     */
    @Override
    public int deletePWxLoginUserByIds(Long[] ids)
    {
        return pWxLoginUserMapper.deletePWxLoginUserByIds(ids);
    }

    /**
     * 删除微信登录用户信息
     * 
     * @param id 微信登录用户主键
     * @return 结果
     */
    @Override
    public int deletePWxLoginUserById(Long id)
    {
        return pWxLoginUserMapper.deletePWxLoginUserById(id);
    }

//    @Transactional
    @Override
    public int bindWX(Map<String, String> accountInfo, String token) {
        String userInfoJson = redisTemplate.opsForValue().get(token)!=null?redisTemplate.opsForValue().get(token).toString():"";
        WXUserLoginInfo wxUserLoginInfo = null;
        if (StringUtils.isNotEmpty(userInfoJson)){
            wxUserLoginInfo = JSON.parseObject(userInfoJson, WXUserLoginInfo.class);
        }
        //未进行微信授权
        if (wxUserLoginInfo == null){
            return 0;
        }
        //校验是否已经绑定账号
        PWxLoginUser pWxLoginUser = pWxLoginUserMapper.selectPWxLoginUserByOpenId(wxUserLoginInfo.getOpenId());
        if (pWxLoginUser!=null){
            //该微信已经绑定账号
            return 0;
        }
        //检查信息是否正确
        String loginType = accountInfo.get("loginType");

        pWxLoginUser = new PWxLoginUser();
        if ("1".equals(loginType)){
            //经销商绑定
            String loginName = accountInfo.get("loginName");
            String password = MD5Utils.md5Hex(accountInfo.get("password"),loginName);
            PDealerLogin pDealerLogin = pDealerLoginMapper.selectPDealerLoginByLoginNameAndPassword(loginName);

            if (pDealerLogin == null){
                //账号密码错误
                return 0;
            }

            pWxLoginUser.setLoginName(loginName);
            pWxLoginUser.setContactId(pDealerLogin.getDealerId());
        }else if("2".equals(loginType)){
            Long schoolId = Long.valueOf(accountInfo.get("schoolId"));
            PSchool pSchool = pSchoolMapper.selectPSchoolById(schoolId);
            String phone = accountInfo.get("phone");
            String detailAddress = accountInfo.get("detailAddress");
            //学校绑定
            PUserAddress pUserAddress = new PUserAddress();
            BeanUtils.copyProperties(pSchool,pUserAddress);
            pUserAddress.setDelFlag("0");
            pUserAddress.setPhone(phone);
            pUserAddress.setSchoolId(schoolId);
            pUserAddress.setStatus("0");
            pUserAddress.setOpenId(wxUserLoginInfo.getOpenId());
            pUserAddress.setDetailAddress(detailAddress);
            pWxLoginUser.setContactId(schoolId);
            //默认新增一个地址
            pUserAddressMapper.insertPUserAddress(pUserAddress);
        }else {
            return 0;
        }

        //新增绑定记录
        pWxLoginUser.setDelFlag("0");
        pWxLoginUser.setOpenId(wxUserLoginInfo.getOpenId());
        pWxLoginUser.setLoginType(loginType);
        pWxLoginUser.setStatus("0");
        pWxLoginUser.setLoginUrl(wxUserLoginInfo.getAvatarUrl());
        pWxLoginUser.setCreateTime(new Date());
        pWxLoginUser.setUpdateTime(new Date());
        pWxLoginUserMapper.insertPWxLoginUser(pWxLoginUser);
        return 1;
    }

    @Override
    public String login(LoginDto dto) {
        String loginType = dto.getLoginType();
        PWxLoginUser pWxLoginUser = null;
        if ("1".equals(loginType)){
            //经销商登录
            if (StringUtils.isEmpty(dto.getLoginName())||StringUtils.isEmpty(dto.getPassword())
                    ||StringUtils.isEmpty(dto.getOpenId())){
                throw new RuntimeException("参数有误！");
            }
            String password = MD5Utils.md5Hex(dto.getPassword(),dto.getLoginName());
            pWxLoginUser = pWxLoginUserMapper.selectPWxLoginUserByOpenId(dto.getOpenId());
            if (pWxLoginUser == null&&!dto.getLoginName().equals(pWxLoginUser.getLoginName())){
                throw new RuntimeException("账号或密码有误！");
            }
            PDealerLogin pDealerLogin = pDealerLoginMapper.selectPDealerLoginByLoginNameAndPassword(dto.getLoginName());
            if (pDealerLogin == null){
                throw new RuntimeException("账号或密码有误！");
            }
        }else if ("2".equals(loginType)){
            //学校登录
            pWxLoginUser = pWxLoginUserMapper.selectPWxLoginUserByOpenId(dto.getOpenId());
            if (pWxLoginUser == null){
                throw new RuntimeException("用户不存在！");
            }
        }else {
            throw new RuntimeException("参数有误！");
        }
        PWxUser pWxUser = pWxUserMapper.selectPWxUserByOpenId(pWxLoginUser.getOpenId());
        //保存用户信息
        String token = MD5Utils.encodeHexString(pWxLoginUser.getOpenId().getBytes());
        WXUserLoginInfo  wxUserLoginInfo = new WXUserLoginInfo();
        BeanUtils.copyProperties(pWxUser,wxUserLoginInfo);
        wxUserLoginInfo.setUserId(pWxUser.getId());
        wxUserLoginInfo.setAvatarUrl(pWxUser.getAvatarUrl());
        wxUserLoginInfo.setLoginType(loginType);
        redisTemplate.opsForValue().set(token,JSON.toJSONString(wxUserLoginInfo),5l, TimeUnit.MILLISECONDS);
        return token;
    }
    @Override
    public LoginUserAndTokenVo bindLoginName(LoginUserAndTokenVo info,LoginDto dto) {
        if(dto.getOpenId() == null && info != null){
            dto.setOpenId(info.getMaOpenId());
        }
        LoginUserAndTokenVo loginUserAndTokenVo = null;
        //经销商登录
        if (StringUtils.isEmpty(dto.getLoginName())||StringUtils.isEmpty(dto.getPassword())
                ||StringUtils.isEmpty(dto.getOpenId())){
            logger.error("账号密码登录参数为空");
            return null;
        }
        //找下微信用户数据
        PWxUser pWxUser = pWxUserMapper.selectPWxUserByOpenId(dto.getOpenId());
        PWxLoginUser pWxLoginUser = null;
        if (pWxUser != null) {
            pWxUser.setUpdateTime(new Date());
            pWxUserMapper.updatePWxUser(pWxUser);
            //后续可以增加经销商只能登陆一个微信用户TODO
            pWxLoginUser = pWxLoginUserMapper.selectPWxLoginUserByOpenId(dto.getOpenId());
            if(pWxLoginUser != null && StringUtils.isNotEmpty(pWxLoginUser.getLoginName())  && !pWxLoginUser.getLoginName().equals(dto.getLoginName())){
                //登录账号不一致
                loginUserAndTokenVo = new LoginUserAndTokenVo();
                loginUserAndTokenVo.setLoginType("-5");
                return loginUserAndTokenVo;
            }

        }else{
            pWxUser = new PWxUser();
            pWxUser.setOpenId(dto.getOpenId());
            pWxUser.setUpdateTime(new Date());
            pWxUser.setCreateTime(new Date());
            pWxUserMapper.insertPWxUser(pWxUser);
        }
//        String password = MD5Utils.md5Hex(dto.getPassword()+dto.getLoginName(),"UTF-8");
        PDealerLogin pDealerLogin = pDealerLoginMapper.selectPDealerLoginByLoginNameAndPassword(dto.getLoginName());
        if (pDealerLogin == null){
            return null;
        }
        if(!pDealerLogin.getPassword().equals(dto.getPassword())){
            loginUserAndTokenVo = new LoginUserAndTokenVo();
            loginUserAndTokenVo.setLoginType("-3");
            return loginUserAndTokenVo;
        }

        PDealer pDealer = pDealerMapper.selectPDealerById(pDealerLogin.getDealerId());
        if (pDealer == null){
            loginUserAndTokenVo = new LoginUserAndTokenVo();
            loginUserAndTokenVo.setLoginType("-5");
            return loginUserAndTokenVo;
        }

        PWxLoginUser pWxLoginUser2 = new PWxLoginUser();
        pWxLoginUser2.setLoginName(pDealerLogin.getLoginName());//经销商登录账号
        List<PWxLoginUser> pWxLoginUsers = pWxLoginUserMapper.selectPWxLoginUserList(pWxLoginUser2);
        if(!pWxLoginUsers.isEmpty()){
            if(!pWxLoginUsers.get(0).getOpenId().equals(dto.getOpenId())){
                loginUserAndTokenVo = new LoginUserAndTokenVo();
                loginUserAndTokenVo.setLoginType("-4");
                return loginUserAndTokenVo;
            }
        }
        loginUserAndTokenVo = new LoginUserAndTokenVo();
        if (pWxLoginUser == null){
            //直接建立登录账号
            pWxLoginUser = new PWxLoginUser();
            pWxLoginUser.setOpenId(dto.getOpenId());
            pWxLoginUser.setLoginName(pDealerLogin.getLoginName());//经销商登录账号
            pWxLoginUser.setLoginType("1");
            if(pWxUser != null){
                pWxLoginUser.setLoginUrl(pWxUser.getAvatarUrl());
                pWxLoginUser.setContactId(pDealerLogin.getDealerId());
                pWxLoginUser.setNickName(pWxUser.getNickName());
                pWxLoginUser.setPhone(pWxUser.getPhone());
            }
            pWxLoginUser.setNickName(pDealer.getDealerName());
            pWxLoginUser.setStatus("2");
            pWxLoginUser.setContactId(pDealer.getId());
            pWxLoginUser.setCreateTime(new Date());
            pWxLoginUser.setUpdateTime(new Date());
            PFileInfo fileInfo = new PFileInfo();
            fileInfo.setContactId(pDealer.getId());
            List<PFileInfo> pFileInfos = fileInfoMapper.selectPFileInfoList(fileInfo);
            if(!pFileInfos.isEmpty()){
                pWxLoginUser.setLoginUrl(pFileInfos.get(0).getFileUrl());
            }
            pWxLoginUserMapper.insertPWxLoginUser(pWxLoginUser);
        }else{
            pWxLoginUser.setLoginName(pDealerLogin.getLoginName());//默认手机号
            pWxLoginUser.setStatus("2");
            pWxLoginUser.setContactId(pDealer.getId());
            pWxLoginUser.setUpdateTime(new Date());
            pWxLoginUser.setNickName(pDealer.getDealerName());
            PFileInfo fileInfo = new PFileInfo();
            fileInfo.setContactId(pDealer.getId());
            List<PFileInfo> pFileInfos = fileInfoMapper.selectPFileInfoList(fileInfo);
            if(!pFileInfos.isEmpty()){
                pWxLoginUser.setLoginUrl(pFileInfos.get(0).getFileUrl());
            }
            pWxLoginUserMapper.updatePWxLoginUser(pWxLoginUser);

        }
        loginUserAndTokenVo.setLoginType(pWxLoginUser.getLoginType());
        loginUserAndTokenVo.setMaOpenId(dto.getOpenId());
        loginUserAndTokenVo.setToBind("0");
        loginUserAndTokenVo.setSubscribeStatus(pWxLoginUser.getSubscribeStatus());
        String token = MD5Utils.encodeHexString(pWxUser.getOpenId().getBytes());
//        redisTemplate.opsForValue().set(token, JSON.toJSONString(loginUserAndTokenVo), 1,TimeUnit.DAYS);
        loginUserAndTokenVo.setAuthToken(token);
        WxLoginUserVo wxLoginUserVo = new WxLoginUserVo();
        wxLoginUserVo.setLoginName(pWxLoginUser.getLoginName());
        wxLoginUserVo.setNickName(pWxLoginUser.getNickName());
        wxLoginUserVo.setLoginUrl(pWxLoginUser.getLoginUrl());
        wxLoginUserVo.setPhone(pWxLoginUser.getPhone());
        if("1".equals(pWxLoginUser.getLoginType())){
            wxLoginUserVo.setPhone(pWxLoginUser.getLoginName());
        }
        wxLoginUserVo.setLoginUserId(pWxLoginUser.getId());
        loginUserAndTokenVo.setLoginUser(wxLoginUserVo);
        return loginUserAndTokenVo;
    }
    @Override
    public int logout(String token) {
        redisTemplate.delete(token);
        return 1;
    }

    public static void main(String[] args) {
        System.out.println(  MD5Utils.md5Hex("123456","15766813398"));
    }
}
